using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;

namespace MediPlatform.Infeartructure
{
    /// <summary>
    /// 仓储扩展方法
    /// </summary>
    public static class RepositoryExtensions
    {
        /// <summary>
        /// 根据条件获取单个实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="repository">仓储</param>
        /// <param name="predicate">条件表达式</param>
        /// <returns>实体</returns>
        public static async Task<T?> GetAsync<T>(this IBaseRepository<T> repository, Expression<Func<T, bool>> predicate) where T : class
        {
            var all = await repository.GetAll();
            return await all.Where(predicate).FirstOrDefaultAsync();
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="repository">仓储</param>
        /// <param name="entity">实体</param>
        /// <returns>任务</returns>
        public static async Task AddAsync<T>(this IBaseRepository<T> repository, T entity) where T : class
        {
            await repository.Create(entity);
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="repository">仓储</param>
        /// <param name="entity">实体</param>
        /// <returns>任务</returns>
        public static async Task UpdateAsync<T>(this IBaseRepository<T> repository, T entity) where T : class
        {
            await repository.Update(entity);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="repository">仓储</param>
        /// <param name="entity">实体</param>
        /// <returns>任务</returns>
        public static async Task DeleteAsync<T>(this IBaseRepository<T> repository, T entity) where T : class
        {
            // 这里需要根据实际的仓储实现来调整
            // 暂时使用Update方法，实际应该实现Delete方法
            await repository.Update(entity);
        }

        /// <summary>
        /// 保存更改
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="repository">仓储</param>
        /// <returns>任务</returns>
        public static async Task SaveChangesAsync<T>(this IBaseRepository<T> repository) where T : class
        {
            // 这个方法需要根据实际的仓储实现来调整
            // 暂时返回已完成的任务
            await Task.CompletedTask;
        }

        /// <summary>
        /// 删除实体（同步版本）
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="repository">仓储</param>
        /// <param name="entity">实体</param>
        public static void Delete<T>(this IBaseRepository<T> repository, T entity) where T : class
        {
            // 同步版本的删除方法
            // 这里需要根据实际的仓储实现来调整
        }
    }
} 